<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" class="progress" type="circle" :percentage="percentage" status="success" />
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDRhhQsDKBl46rhHbeQv95k9G9oCJ9hyzn',
  SecretKey: 'auxjERN2SdXAWbOvBHAn9E2ZptlNjpeC'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      showProgress: false

    }
  },
  methods: {
    upload(files) {
      if (files.file) {
        this.showProgress = true
        cos.putObject({
          Bucket: 'zqq-1308159382', /* 必须 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: files.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = progressData.percent * 100
            // console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          if (err === null) {
            this.imageUrl = `https:${data.Location}`
          }
          this.showProgress = false
        })
      }
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<style lang="scss" scoped>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>

